const { showLoading, hideLoading } = require('../../utils/util')
const _ = require('../../services/checklist')
const app = getApp()

Page({
  data: {
    checklist: {
      icon: '',
      title: '我的一天',
      isStatic: true
    },
    tasks: [],
    addTaskModalVisible: false,
    audioAction: {
      method: 'pause'
    },
    animations: {
    }
  },

  onLoad: function (options) {
    const _this = this
    if (app.state.userInfo.id) {
      showLoading()
      _.fetch(app.state.userInfo.id).then((data) => {
        _this.init(data)
        hideLoading()
      })
    } else {
      app.fetchChecklistsCallback = (userId) => {
        if (userId) {
          showLoading()
          _.fetch(app.state.userInfo.id).then((data) => {
            _this.init(data)
            hideLoading()
          })
        }
      }
    }
  },
  onShow: function (options) {
    if (app.state.checklists.length > 0) {
      this.handleOnShow()
    }
  },
  onReady: function () {
    this.headerAnimation = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease-in-out'
    })
    this.titleAnimation = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease-in-out'
    })
    this.audioCtx = wx.createAudioContext('doneAudio')
  },

  init(data) {
    app.state.checklists = data
    this.handleOnShow()
  },
  handleOnShow() {
    const { cid } = app.state
    let icon = ''
    let title = '我的一天'
    let isStatic = true
    const tasks = []
    if (cid === "0") {
      app.state.checklists.forEach((u) => {
        const todays = u.tasks.filter((v) => v.today)
        todays.forEach((v) => {
          v.listId = u.id
          v.listName = u.title
        })
        tasks.push(...todays)
      });
    } else {
      const checklist = app.state.checklists.find((u) => u.id === cid)
      icon = (checklist.icon === 'todo' || checklist.icon === 'list')
        ? '' : checklist.icon
      title = checklist.title
      isStatic = checklist.isStatic
      tasks.push(...checklist.tasks)
    }

    this.setData({
      'checklist.icon': icon,
      'checklist.title': title,
      'checklist.isStatic': isStatic,
      tasks
    })
  },
  handleSwitch: function (e) {
    wx.navigateTo({
      url: '../menu/index'
    })
  },
  handleMore: function (e) {
    const { isStatic } = this.data.checklist
    const itemList = []
    if (!isStatic) {
      itemList.push("删除清单")
    }

    if (itemList.length > 0) {
      const _this = this
      wx.showActionSheet({
        itemList,
        success: function ({ tapIndex }) {
          const tap = itemList[tapIndex]
          if (tap === '删除清单') {
            wx.showModal({
              title: '你确定吗？',
              content: `"${_this.data.checklist.title}"将被永远删除`,
              success: function (res) {
                if (res.confirm) {
                  _.deleteChecklist(app.state.cid).then((data) => {
                    hideLoading()
                    app.deleteChecklist(app.state.cid)
                    wx.showToast({
                      title: '删除成功',
                      icon: 'success',
                      success: function () {
                        app.state.cid = '0'
                        wx.redirectTo({ url: './index' })
                      }
                    })
                  }).catch(({ code }) => {
                    hideLoading()
                    if (code && code === 4005) {
                      wx.showToast({
                        title: '清单不存在',
                        icon: 'none'
                      })
                    }
                  })
                }
              }
            })
          }
        }
      })
    }
  },
  handleTitleClicked: function (e) {
    console.log('clicked!')
  },
  handleTouchmoving: function (e) {
    if (!this.lastClientY) {
      this.lastClientY = e.touches[0]['clientY']
    } else if (this.lastClientY > e.touches[0]['clientY']) {
      // 向上滑则缩小标题
      this.lastClientY = e.touches[0]['clientY']
      this.animationContractHeader()
    } else {
      // 向下滑则扩大标题
      this.lastClientY = e.touches[0]['clientY']
      this.animationExpandHeader()
    }
  },
  handleTouchend: function (e) {
    this.lastClientY = undefined
  },
  animationExpandHeader: function () {
    if (this.data.animations.status) {
      this.setData({
        'animations.header': this.headerAnimation.scale(1).translateX(0).translateY(0).height(150).step().export(),
        'animations.title': this.titleAnimation.scale(1).translateX(15).translateY(90).step().export(),
        'animations.status': false
      })
    }
  },
  animationContractHeader: function () {
    if (!this.data.animations.status) {
      this.setData({
        'animations.header': this.headerAnimation.height(50).step().export(),
        'animations.title': this.titleAnimation.scale(0.75).translateX(45).translateY(0).step().export(),
        'animations.status': true
      })
    }
  },
  showAddNewTaskModal: function () {
    this.setData({
      'addTaskModalVisible': true
    })
  },

  addNewTask: function ({ detail: todo }) {
    showLoading()
    const payload = {
      todo,
      listId: app.getCurrentChecklistId()
    }
    if (app.state.cid === "0") {
      _.addTodayTask(payload).then((data) => {
        const todoList = app.state.checklists.find((u) => u.isStatic)
        data.index = todoList.tasks.length
        data.listId = todoList.id
        data.listName = todoList.title
        todoList.tasks.push(data)
        this.setData({
          'tasks': [...this.data.tasks, data],
          'addTaskModalVisible': false
        })
        hideLoading()
      })
    } else {
      _.addNewTask(payload).then((data) => {
        const currentList = app.state.checklists.find((u) => u.id === payload.listId)
        data.index = currentList.tasks.length
        currentList.tasks.push(data)
        this.setData({
          'tasks': [...this.data.tasks, data],
          'addTaskModalVisible': false
        })
        hideLoading()
      })
    }
  },
  toggleDone: function ({ detail: payload }) {
    const _this = this
    _.toggleDoneTask(payload).then((data) => {
      const { listId, index, isDone } = payload
      app.updateSpecifiedTaskField(listId, index, 'isDone', isDone)
      const _index = this.data.tasks.findIndex((v) =>
        // myday
        (v.listId && v.listId === listId && v.index === index) ||
        // others
        (!v.listId && v.index === index)
      )
      this.setData({
        [`tasks[${_index}].isDone`]: isDone
      })
      if (isDone) {
        _this.audioCtx.play()
      }
    })
  },
  toggleToday: function ({ detail: payload }) {
    _.toggleMydayTask(payload).then((data) => {
      const { listId, index, today } = payload
      app.updateSpecifiedTaskField(listId, index, 'today', today)
      if (app.state.cid === "0") {
        // myday
        this.setData({
          tasks: this.data.tasks.filter((v) => (v.listId !== listId) || (v.listId === listId && v.index !== index))
        })
      } else {
        // others
        const _index = this.data.tasks.findIndex((v) => v.index === index)
        this.setData({
          [`tasks[${_index}].today`]: today
        })
      }
    })
  },
  deleteTask: function ({ detail: { todo, ...payload } }) {
    const _this = this
    wx.showModal({
      title: '删除待办事项',
      content: `"${todo}"就被永远删除。`,
      success: function ({ confirm }) {
        if (confirm) {
          _.deleteTask(payload).then((data) => {
            const { listId, index } = payload
            app.deleteSpecifiedTask(listId, index)
            if (app.state.cid === '0') {
              _this.setData({
                tasks: _this.data.tasks.filter((u) => !(u.listId === listId && u.index === index))
              })
            } else {
              _this.setData({
                tasks: _this.data.tasks.filter((u) => u.index !== index)
              })
            }
          })
        }
      }
    })
  }
})
